import XLSX from 'xlsx'
import fs from 'fs'

export function export2Excel (json, wsName) {
  if (!json.length) return false

  let workbook = XLSX.utils.book_new()
  const ws = XLSX.utils.json_to_sheet(json)

  XLSX.utils.book_append_sheet(workbook, ws, wsName)
  XLSX.writeFile(workbook, wsName + '.xlsx')
}

export function export2CSV (json, wsName) {
  if (!json.length) return false

  const ws = XLSX.utils.json_to_sheet(json)
  const csv = XLSX.utils.sheet_to_csv(ws)

  return new Promise((resolve, reject) => {
    fs.writeFile(wsName + '.csv', csv, function (err) {
      if (err) {
        throw (err)
      } else {
        return wsName + '.csv'
      }
    })
  })
}
